package cn.fintecher.pangolin.service.report.service;

import cn.fintecher.pangolin.common.enums.TaskBoxStatus;
import cn.fintecher.pangolin.common.enums.TaskBoxType;
import cn.fintecher.pangolin.common.exception.BadRequestException;
import cn.fintecher.pangolin.common.model.DepartmentModel;
import cn.fintecher.pangolin.common.model.TaskBoxModel;
import cn.fintecher.pangolin.common.model.UploadFile;
import cn.fintecher.pangolin.common.model.UserModel;
import cn.fintecher.pangolin.common.response.LoginResponse;
import cn.fintecher.pangolin.common.utils.InnerServiceUrl;
import cn.fintecher.pangolin.common.utils.ZWDateUtil;
import cn.fintecher.pangolin.service.report.client.WebSocketClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

/**
 * @Auther: xiaqun
 * @Description:
 * @Date: 10:55 2019/8/14
 */

@Service("baseService")
public class BaseService {
    @Autowired
    private RedisTemplate<String, Object> jsonRedisTemplate;

    @Autowired
    private WebSocketClient webSocketClient;

    @Autowired
    private RestTemplate restTemplate;

    /**
     * 获取用户信息
     */
    public UserModel getUserByToken(String token) {
        LoginResponse response = (LoginResponse) jsonRedisTemplate.opsForValue().get(token);
        if (Objects.isNull(response)) {
            throw new BadRequestException(null, "user", "token.is.error");
        }
        return response.getUserModel();
    }

    /**
     * 获取用户部门信息
     */
    DepartmentModel getDepartmentByToken(String token) {
        LoginResponse response = (LoginResponse) jsonRedisTemplate.opsForValue().get(token);
        if (Objects.isNull(response)) {
            throw new BadRequestException(null, "user", "token.is.error");
        }
        return response.getDepartmentModel();
    }

    public LoginResponse getUserSessionByToken(String token) {
        LoginResponse response = (LoginResponse) jsonRedisTemplate.opsForValue().get(token);
        if (Objects.isNull(response)) {
            throw new BadRequestException(null, "user", "token.is.error");
        }
        return response;
    }

    /**
     * 处理多线程集合
     */
    static <T> List<T> processList(List<CompletableFuture<T>> list) {
        List<T> tList = new ArrayList<>();
        try {
            for (CompletableFuture<T> future : list) {
                tList.add(future.get());
            }
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
        return tList;
    }

    /**
     * 生成任务盒子
     */
    public TaskBoxModel getTaskBox(TaskBoxType type, String description, UserModel userModel) {
        TaskBoxModel model = new TaskBoxModel();
        model.setId(UUID.randomUUID().toString().replaceAll("-", ""));
        sendTaskBoxMessage(model, type, TaskBoxStatus.UN_FINISH, null, null, userModel, ZWDateUtil.getNowDateTime(), null, description);
        return model;
    }

    public TaskBoxModel sendTaskBoxMessage(TaskBoxModel model, TaskBoxType taskBoxType, TaskBoxStatus taskBoxStatus,
                                           String fileId, String fileName, UserModel userModel, Date startTime, Date endTime, String taskDescribe) {
        model.setTaskBoxType(taskBoxType);
        model.setTaskBoxStatus(taskBoxStatus);
        model.setFileId(fileId);
        model.setFileName(fileName);
        model.setOperator(userModel.getId());
        model.setOperatorTime(ZWDateUtil.getNowDateTime());
        if (Objects.nonNull(taskDescribe)) {
            model.setTaskDescribe(taskDescribe);
        }
        if (Objects.nonNull(startTime)) {
            model.setBeginDate(startTime);
        }
        if (Objects.nonNull(endTime)) {
            model.setEndDate(endTime);
        }
        webSocketClient.sendTaskByUserId(model, userModel.getUsername());
        return model;
    }

    /***
     *上传路径
     * @param filePath
     * @return
     */
    public UploadFile getFileUrl(String filePath) {
        FileSystemResource resource = new FileSystemResource(filePath);
        MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();
        param.add("file", resource);
        ResponseEntity<UploadFile> response = restTemplate.postForEntity(InnerServiceUrl.COMMON_SERVICE_UPLOADFILE, param, UploadFile.class);
        return response.getBody();
    }

    /**
     * 生成tet文件并返回文件ID
     */
    public String generateTxt(List<String> list, String butchNumber) {
        OutputStreamWriter osw = null;
        BufferedWriter bw;
        File file = null;
        try {
            //生成txt文件
            String path = "/home/temp/" + butchNumber + ".txt";
            file = new File(path);
            if (!file.exists()) {
                file.getParentFile().mkdirs();
            }
            file.createNewFile();
            osw = new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8);
            bw = new BufferedWriter(osw);
            for (String s : list) {
                bw.write(s);
                bw.newLine();
            }
            bw.flush();
            //上传文件服务器
            FileSystemResource resource = new FileSystemResource(file);
            MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();
            param.add("file", resource);
            ResponseEntity<UploadFile> entity = restTemplate.postForEntity("http://common-service/api/uploadFile/upload", param, UploadFile.class);
            if (entity.hasBody()) {
                UploadFile uploadFile = entity.getBody();
                return uploadFile.getId();
            } else {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            //删除临时文件
            if (Objects.nonNull(file)) {
                if (file.exists() && file.isFile()) {
                    File file1 = new File(file.getAbsolutePath());
                    file1.delete();
                }
            }
        }
    }
}
